﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ScrumTime.Models;
using ScrumTime.ViewModels;
using ScrumTime.Helpers;
using ScrumTime.Services;

namespace ScrumTime.Controllers
{
    public class StoryController : Controller
    {
        ScrumTimeEntities _ScrumTimeEntities;
        StoryService _StoryService;

        TaskService _TaskService;
        AcceptanceCriteriaService _AcceptanceCriteriaService;


        public StoryController()
        {
            _ScrumTimeEntities = new ScrumTimeEntities();
            _StoryService = new StoryService(_ScrumTimeEntities);
            _TaskService = new TaskService(_ScrumTimeEntities);
            _AcceptanceCriteriaService = new AcceptanceCriteriaService(_ScrumTimeEntities);
        }

        // The backlog is the entire html page
        [Authorize]
        public ActionResult BacklogByPriority()
        {
            // TODO: Pull the actual product information from session before 0.9 release
            StoryCollectionViewModel storyCollectionViewModel = StoryCollectionViewModel.BuildByPriorityAsc(
                SessionHelper.GetCurrentProductId(User.Identity.Name, Session));
            return PartialView("Backlog", storyCollectionViewModel);
        }

        // The list is the sub-section of the page that contains only the table of story read only rows
        [Authorize]
        public ActionResult ListByPriority()
        {
            // TODO: Pull the actual product information from session before 0.9 release
            StoryCollectionViewModel storyCollectionViewModel = StoryCollectionViewModel.BuildByPriorityAsc(
                SessionHelper.GetCurrentProductId(User.Identity.Name, Session));           
            return PartialView("List", storyCollectionViewModel);
        }

        // Returns only one read only row
        [Authorize]
        public ActionResult ReadOnly(int id)
        {
            Story story = _StoryService.GetStoryById(id);
            return PartialView(story);
        }


        private List<UsabilityFeature> addUsabilityFeaturesString(Story story, string usabilityFeatures_string)
        {

            List<UsabilityFeature> resultado = new List<UsabilityFeature>();

            string[] s_ufs = usabilityFeatures_string.Split('-');
            foreach (string s_uf in s_ufs)
            {
                if (s_uf.Length > 0) {
                    UsabilityFeature uf = UsabilityFeatureService.GetUsabilityFeatureById(_ScrumTimeEntities, int.Parse(s_uf) );                   
                    resultado.Add(uf);
                }
            }
            return resultado;
        }




        // POST: /Story/Save
        [Authorize]
        [HttpPost]
        public ActionResult Save(FormCollection collection)
        {
            try
            {

                string id = collection.Get("storyId");
                bool newStory = false;
                if (id == null || id == "0")
                {
                    id = "0";
                    newStory = true;
                }
                string priority = collection.Get("priority");
                string originalPriority = collection.Get("originalPriority");
                string userDefinedId = collection.Get("userDefinedId");
                string narrative = collection.Get("narrative");
                string points = collection.Get("points");
                string sprintId =  collection.Get("sprintId") ;

                userDefinedId = UtilServices.ReplaceQuote(userDefinedId);
                narrative = UtilServices.ReplaceQuote(narrative);


                string usabilityFeatures_string = collection.Get("usabilityFeatures");

                int? sprintIdAsInt = (sprintId == null) ? null : (int?)Int32.Parse(sprintId);
                sprintIdAsInt = (sprintIdAsInt != null && sprintIdAsInt > 0) ? sprintIdAsInt : null;
                // TODO:  Validate the story data before saving
                // TODO:  Set the correct product id
                Story story = new Story()
                {
                    StoryId = Int32.Parse(id),
                    Narrative = narrative,
                    Points = Int32.Parse(points),
                    Priority = Int32.Parse(priority),
                    ProductId = SessionHelper.GetCurrentProductId(User.Identity.Name, Session),
                    UserDefinedId = userDefinedId                    
                };

                if( sprintIdAsInt != -1 ){
                    story.SprintId = sprintIdAsInt;
                }
                

                List < UsabilityFeature > lista_uf = addUsabilityFeaturesString(story, usabilityFeatures_string);
                story = _StoryService.SaveStory(story, lista_uf);                
                
                return View("ShowStory", story);
            }
            catch (Exception e)
            {
                return Redirect(ScrumTime.Helpers.ErrorHelper.GetURLGeneralError(e.Message));                 
            }
        }

        //
        // GET: /Story/Delete/5
        [Authorize]
        public ActionResult Delete(int id)
        {
            // TODO: Provide a caution prior to delete...use this GET delete to display a warning.
            return View();
        }

        //
        // POST: /Story/Delete/5
        [Authorize]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                string idAsString = collection.Get("storyId");
                _StoryService.DeleteStory(Int32.Parse(idAsString));
                return RedirectToAction("ListByPriority", new { displayPartial = true });
            }
            catch (Exception e)
            {
                return Redirect(ScrumTime.Helpers.ErrorHelper.GetURLGeneralError(e.Message) ); 
                //return View();
            }
        }

        
        [Authorize]
        [HttpPost]
        public ActionResult DeleteAssociation(FormCollection collection)
        {
            try
            {
                string s_storyId = collection.Get("storyId");
                string s_relatedStoryId = collection.Get("relatedStoryId");

                _StoryService.removeAssociation(Int32.Parse(s_storyId), int.Parse(s_relatedStoryId));

                //_StoryService.DeleteStory(Int32.Parse(idAsString));                
                return View("ShowUsabilityStory", _StoryService.GetStoryById(int.Parse(s_storyId)));
            }
            catch (Exception e)
            {
                return Redirect(ScrumTime.Helpers.ErrorHelper.GetURLGeneralError(e.Message) ); 
                //return View();
            }
        }
   
        // Returns the entire Backlog html page
        [Authorize]
        public ActionResult Index()
        {
            return RedirectToAction("BacklogByPriority");
        }

        // Returns the entire Backlog html page
        [Authorize]
        public ActionResult ShowStory(FormCollection collection)
        {
            //Story story = _StoryService.GetStoryById(storyId);
            //return View(story);
            string idAsString = collection.Get("id");
            
            Story story = _StoryService.GetStoryById(int.Parse(idAsString));
            return View(story);
        }

        // Returns the entire Backlog html page
        [Authorize]
        public ActionResult ShowStory_BasicData_Task_Edit(FormCollection collection)
        {
            //Story story = _StoryService.GetStoryById(storyId);
            //return View(story);
            int idTask = int.Parse( collection.Get("id"));
            int idAffectedTask = int.Parse(collection.Get("idAffectedTask"));
            int idStory = int.Parse(collection.Get("idStory"));

            Task t=  _TaskService.GetTaskById(idTask);

            if (idAffectedTask != -1) {
                UsabilityAffectedTask uaffectedTask = UsabilityAffectedTaskService.GetUsabilityAffectedTaskById(_ScrumTimeEntities, idAffectedTask);
                t.Description = uaffectedTask.Description;
                t.UsabilityAffectedTasks.Add(uaffectedTask);
            }

            t.StoryId = idStory;

            return View(t);
        }


        // Returns the entire Backlog html page
        [Authorize]
        public ActionResult ShowStoryHelp(FormCollection collection)
        {            
            int idUsability_Task_UC = int.Parse( collection.Get("id"));
            int helpId = int.Parse(collection.Get("HelpId"));
            String type = collection.Get("type");

            //falta esta parte por hacer!

            ScrumTime.Models.HelpModel help = new ScrumTime.Models.HelpModel();

            help.id = idUsability_Task_UC;
            help.HelpId = helpId;
            help.type = type;
            //if (type == "task")
            //{
            //    help.type = ScrumTime.Models.HelpModel.TASK;
            //}
            //else {
            //    help.type = ScrumTime.Models.HelpModel.USABILITY_CRITERIA;
            //}
            //aqui recuperamos el tipo y el ide, y em base a esos datos mostramos la ayuda correspondiente
            return View(help);
        }


        [Authorize]
        public ActionResult ShowStory_Tasks(FormCollection collection)
        {
            string idAsString = collection.Get("id");
            Story story = _StoryService.GetStoryById(int.Parse(idAsString));
            return View(story);
        }

        // Returns the entire Backlog html page
        [Authorize]
        public ActionResult ShowStory_BasicData_AcceptanceCriteria_Edit(FormCollection collection)
        {
            //Story story = _StoryService.GetStoryById(storyId);
            //return View(story);
            int idAcceptanceCriteria = int.Parse( collection.Get("id"));
            int idAffectedAC = int.Parse(collection.Get("idAffectedAcceptanceCriteria"));
            int idStory = int.Parse(collection.Get("idStory"));

            
            AcceptanceCriteria ac=  _AcceptanceCriteriaService.GetAcceptanceCriteriaById(idAcceptanceCriteria);

            if (idAffectedAC != -1) {
                UsabilityAffectedAcceptanceCriteria uaffectedAC = UsabilityAffectedAcceptanceCriteriaService.GetUsabilityAffectedAcceptanceCriteriaById(_ScrumTimeEntities, idAffectedAC);
                ac.Description = uaffectedAC.Description;
                ac.UsabilityAffectedAcceptanceCriterias.Add(uaffectedAC);
            }

            ac.StoryId = idStory;

            return View(ac);
        }

        [Authorize]
        public ActionResult ShowStory_AcceptanceCriterias(FormCollection collection)
        {
            string idAsString = collection.Get("id");
            Story story = _StoryService.GetStoryById(int.Parse(idAsString));
            return View(story);
        }

        

    }
}
